package cn.org.timespace.easyframe.dao.permission.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;

import cn.org.timespace.easyframe.action.permission.EFMenuModel;
import cn.org.timespace.easyframe.dao.EfBaseDAO;
import cn.org.timespace.easyframe.dao.permission.EfMenuDao;
import cn.org.timespace.easyframe.model.permission.EfMenu;

/**
 * A data access object (DAO) providing persistence and search support for
 * EfMenu entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see com.model.EfMenu
 * @author MyEclipse Persistence Tools
 */

public class EfMenuDaoImpl extends EfBaseDAO implements EfMenuDao {
	// property constants 

	public void save(EfMenu transientInstance) {
		log.debug("saving EfMenu instance");
		try {
			getSession().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(EfMenu persistentInstance) {
		log.debug("deleting EfMenu instance");
		try {
			getSession().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}


	public List<EfMenu> findByCondition(EFMenuModel model) {
		log.debug("finding all EfMenu instances");
		try {
			StringBuffer queryString = new StringBuffer("from EfMenu a where 1=1 ");
			
			if(!StringUtils.isEmpty(model.getMenuId())){
				queryString.append("and a.menuId = '"+model.getMenuId().trim()+"' ");
			}
			
			if(!StringUtils.isEmpty(model.getMenuUrl())){
				queryString.append("and a.menuIsValid like '%"+model.getDicMenuIsValid().trim()+"%' ");
			}
			
			if(!StringUtils.isEmpty(model.getMenuName())){
				queryString.append("and a.menuName like '%"+model.getMenuName().trim()+"%' ");
			}
			
			if(!StringUtils.isEmpty(model.getMenuPhotoUrl())){
				queryString.append("and a.menuPhotoUrl like '%"+model.getMenuPhotoUrl().trim()+"%' ");
			}
			
			if(!StringUtils.isEmpty(model.getParentMenuId())){
				queryString.append("and a.parentMenuId like '%"+model.getParentMenuId().trim()+"%' ");
			}
			
			if(!StringUtils.isEmpty(model.getDicMenuIsValid())){
				queryString.append("and a.dicMenuIsValid = '"+model.getDicMenuIsValid()+"' ");
			}
			
			queryString.append(" order by a.menuId asc,a.displayNo asc");
			
			return getHibernateTemplate().find(queryString.toString());
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}
	

	public List<EfMenu> findSecondLevelMenu() {
		log.debug("finding second level EfMenu instances");
		try {
			String queryString = "from EfMenu a where a.parentMenuId != '0' and a.dicMenuIsValid = '1'  order by a.displayNo asc ";
			return getHibernateTemplate().find(queryString.toString());
		} catch (RuntimeException re) {
			log.error("findSecondLevelMenu failed", re);
			throw re;
		}
	}

	public List<EfMenu> findTopLevelMenu() {
		log.debug("finding top level EfMenu instances");
		try {
			String queryString = "from EfMenu a where a.parentMenuId = '0' and a.dicMenuIsValid = '1' order by a.displayNo asc";
			return getHibernateTemplate().find(queryString.toString());
		} catch (RuntimeException re) {
			log.error("findTopLevelMenu failed", re);
			throw re;
		}
	}

	public void update(EfMenu instance) {
		getHibernateTemplate().update(instance);
	}
	
	public List<EfMenu> findTopLevelMenu(String userId) {
		log.debug("finding top level EfMenu instances");
		
		Session session = null;
		Query query = null;
		
		List<EfMenu> resList = new ArrayList<EfMenu>();
		try {
			StringBuffer queryString = new StringBuffer();
			queryString.append(" SELECT DISTINCT m.*                                                          ");
			queryString.append(" FROM EF_USER_ROLE ur,EF_ROLE_MENU rm,EF_MENU m  ");
			queryString.append(" WHERE rm.ROLE_ID = ur.ROLE_ID                                          ");
			queryString.append(" AND m.MENU_ID = rm.MENU_ID                                          ");
			queryString.append(" AND ur.USER_ID = '"+userId+"'                                        ");
			queryString.append(" AND m.PARENT_MENU_ID = '0'                                          ");
			queryString.append(" AND m.DIC_MENU_IS_VALID = '1'                                       ");
			queryString.append(" ORDER BY m.DISPLAY_NO ASC                                           ");
			
			
			session = getSessionFactory().openSession();
			query = session.createSQLQuery(queryString.toString());
			List list = query.list();
			
			if(list != null && list.size() > 0){
				for(int i=0;i<list.size();i++)
				{
					Object[] obj = (Object[])list.get(i);
					EfMenu efMenu = new EfMenu();
					efMenu.setMenuId(obj[0] != null ? obj[0].toString() : null);
					efMenu.setParentMenuId(obj[1] != null ? obj[1].toString() : null);
					efMenu.setMenuName(obj[2] != null ? obj[2].toString() : null);
					efMenu.setMenuUrl(obj[3] != null ? obj[3].toString() : null);
					efMenu.setDisplayNo(obj[4] != null ? Short.valueOf(obj[4].toString()) : null);
					efMenu.setMenuPhotoUrl(obj[5] != null ? obj[5].toString() : null);
					efMenu.setDicMenuIsValid(obj[6] != null ? obj[6].toString() : null);
					efMenu.setLinkType(obj[7] != null ? obj[7].toString() : null);
					efMenu.setTarget(obj[8] != null ? obj[8].toString() : null);
					resList.add(efMenu);
				}
			}
			
			return resList;
			
		} catch (RuntimeException re) {
			log.error("findTopLevelMenu failed", re);
			throw re;
		}finally{
			if(session != null) session.close();
			if(query != null) query = null;
		}
		
	}

	public List<EfMenu> findSecondLevelMenu(String userId, String modelId) {
		log.debug("finding second level EfMenu instances");
		
		Session session = null;
		Query query = null;
		
		List<EfMenu> resList = new ArrayList<EfMenu>();
		try {
			StringBuffer queryString = new StringBuffer();
				queryString.append(" SELECT DISTINCT m.*                                                          ");
				queryString.append(" FROM EF_USER u,EF_ROLE r,EF_USER_ROLE ur,EF_ROLE_MENU rm,EF_MENU m  ");
				queryString.append(" WHERE u.USER_ID = ur.USER_ID                                        ");
				queryString.append(" AND r.ROLE_ID = ur.ROLE_ID                                          ");
				queryString.append(" AND r.ROLE_ID = rm.ROLE_ID                                          ");
				queryString.append(" AND m.MENU_ID = rm.MENU_ID                                          ");
				queryString.append(" AND u.USER_ID = '"+userId+"'                                        ");
				queryString.append(" AND m.PARENT_MENU_ID = '"+modelId+"'                                ");
				queryString.append(" AND m.DIC_MENU_IS_VALID = '1'                                       ");
				queryString.append(" ORDER BY m.DISPLAY_NO ASC                                           ");
			
			session = getSessionFactory().openSession();
			query = session.createSQLQuery(queryString.toString());
			
			List list = query.list();
			
			if(list != null && list.size() > 0){
				for(int i=0;i<list.size();i++)
				{
					Object[] obj = (Object[])list.get(i);
					EfMenu efMenu = new EfMenu();
					efMenu.setMenuId(obj[0] != null ? obj[0].toString() : null);
					efMenu.setParentMenuId(obj[1] != null ? obj[1].toString() : null);
					efMenu.setMenuName(obj[2] != null ? obj[2].toString() : null);
					efMenu.setMenuUrl(obj[3] != null ? obj[3].toString() : null);
					efMenu.setDisplayNo(obj[4] != null ? Short.valueOf(obj[4].toString()) : null);
					efMenu.setMenuPhotoUrl(obj[5] != null ? obj[5].toString() : null);
					efMenu.setDicMenuIsValid(obj[6] != null ? obj[6].toString() : null);
					efMenu.setLinkType(obj[7] != null ? obj[7].toString() : null);
					efMenu.setTarget(obj[8] != null ? obj[8].toString() : null);					
					resList.add(efMenu);
				}
			}
			
			return resList;
			
		} catch (RuntimeException re) {
			log.error("findSecondLevelMenu failed", re);
			throw re;
		}finally{
			if(session != null) session.close();
			if(query != null) query = null;
		}
	}

	public List<EfMenu> findThirdLevelMenu(String userId, String modelId) {
		log.debug("finding third level EfMenu instances");
		List<EfMenu> resList = new ArrayList<EfMenu>();
		
		Session session = null;
		Query query = null;		
		
		try {
			StringBuffer queryString = new StringBuffer();
			queryString.append("SELECT DISTINCT M.*                                                                ");  
			queryString.append("  FROM EF_USER U, EF_ROLE R, EF_USER_ROLE UR, EF_ROLE_MENU RM, EF_MENU M  ");  
			queryString.append(" WHERE U.USER_ID = UR.USER_ID                                             ");  
			queryString.append("   AND R.ROLE_ID = UR.ROLE_ID                                             ");  
			queryString.append("   AND R.ROLE_ID = RM.ROLE_ID                                             ");  
			queryString.append("   AND M.MENU_ID = RM.MENU_ID                                             ");  
			queryString.append("   AND U.USER_ID = '"+userId+"'                           ");  
			queryString.append("   AND M.DIC_MENU_IS_VALID = '1'                                          ");  
			queryString.append("   AND M.PARENT_MENU_ID IN                                                ");  
			queryString.append("       (SELECT M.MENU_ID                                                  ");  
			queryString.append("          FROM EF_USER      U,                                            ");  
			queryString.append("               EF_ROLE      R,                                            ");  
			queryString.append("               EF_USER_ROLE UR,                                           ");  
			queryString.append("               EF_ROLE_MENU RM,                                           ");  
			queryString.append("               EF_MENU      M                                             ");  
			queryString.append("         WHERE U.USER_ID = UR.USER_ID                                     ");  
			queryString.append("           AND R.ROLE_ID = UR.ROLE_ID                                     ");  
			queryString.append("           AND R.ROLE_ID = RM.ROLE_ID                                     ");  
			queryString.append("           AND M.MENU_ID = RM.MENU_ID                                     ");  
			queryString.append("           AND U.USER_ID = '"+userId+"'                   ");  
			queryString.append("           AND M.PARENT_MENU_ID = '"+modelId+"'                                   ");  
			queryString.append("           AND M.DIC_MENU_IS_VALID = '1')                                 ");  
			queryString.append(" ORDER BY M.DISPLAY_NO ASC                                                ");  
  


			
			session = getSessionFactory().openSession();
			query = session.createSQLQuery(queryString.toString());
			
			List list = query.list();
			
			if(list != null && list.size() > 0){
				for(int i=0;i<list.size();i++)
				{
					Object[] obj = (Object[])list.get(i);
					EfMenu efMenu = new EfMenu();
					efMenu.setMenuId(obj[0] != null ? obj[0].toString() : null);
					efMenu.setParentMenuId(obj[1] != null ? obj[1].toString() : null);
					efMenu.setMenuName(obj[2] != null ? obj[2].toString() : null);
					efMenu.setMenuUrl(obj[3] != null ? obj[3].toString() : null);
					efMenu.setDisplayNo(obj[4] != null ? Short.valueOf(obj[4].toString()) : null);
					efMenu.setMenuPhotoUrl(obj[5] != null ? obj[5].toString() : null);
					efMenu.setDicMenuIsValid(obj[6] != null ? obj[6].toString() : null);
					efMenu.setLinkType(obj[7] != null ? obj[7].toString() : null);
					efMenu.setTarget(obj[8] != null ? obj[8].toString() : null);					
					resList.add(efMenu);
				}
			}
			
			return resList;
			
		} catch (RuntimeException re) {
			log.error("findThirdLevelMenu failed", re);
			throw re;
		}finally{
			if(session != null) session.close();
			if(query != null) query = null;
		}
	}


}